package com.marry.requestLogger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.marry.requestLogger.entity.LoggerEntity;
import com.marry.requestLogger.jpa.loggerJpa;
import com.marry.requestLogger.util.LoggerUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ml
 * @create 2017-07-03--15:07
 */
public class LoggerInterceptor implements HandlerInterceptor {

    //请求开始时间标志
    private static final String LOGGER_SEND_TIME="send_time";

    //请求日志实体标志
    private static final String LOGGER_ENTITY="_logger_entity";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        LoggerEntity logger=new LoggerEntity();

        String sessionId=request.getRequestedSessionId();

        String url=request.getRequestURI();
        String paramData= JSON.toJSONString(request.getParameterMap(),
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue);

        logger.setClientip(LoggerUtils.getCilentIp(request));

        logger.setMethod(request.getMethod());

        logger.setType(LoggerUtils.getRequestType(request));

        logger.setParamData(paramData);

        logger.setClienturi(url);

        logger.setSessionId(sessionId);

        request.setAttribute(LOGGER_SEND_TIME,System.currentTimeMillis());

        request.setAttribute(LOGGER_ENTITY,logger);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

        int status=response.getStatus();

        long currentTime=System.currentTimeMillis();

        long startTime= Long.parseLong(request.getAttribute(LOGGER_SEND_TIME).toString());

        LoggerEntity loggerEntity= (LoggerEntity) request.getAttribute(LOGGER_ENTITY);

        loggerEntity.setTimeConsuming(Integer.valueOf(currentTime-startTime+""));

        loggerEntity.setReturnTime(currentTime+"");


        loggerEntity.setStatus(status+"");

        loggerEntity.setReturnData(JSON.toJSONString(request.getAttribute(LoggerUtils.LOGGER_TETURN),
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue));


        loggerJpa loggerDao=getDAO(loggerJpa.class,request);
        loggerDao.save(loggerEntity);






    }


    /**
     * 根据传入的类型获取spring对应的Dao
     * @param clazz 类型
     * @param request 请求对象
     * @param <T>
     * @return
     */
    private<T> T getDAO(Class<T> clazz,HttpServletRequest request){
        BeanFactory factory= WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());

        return factory.getBean(clazz);


    }


}
